// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package trace_cmd

import (
	"fmt"
	"time"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/trace_api"
	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/utils"
	"github.com/spf13/cobra"
)

var listRootSpanNameCmd_pastHour uint32

var listRootSpanNameCmd = &cobra.Command{
	Use: "listRootSpanName",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 2 {
			return fmt.Errorf("need param [serviceName] [serviceVersion]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.Port.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		serviceName := args[0]
		serviceVersion := args[1]

		client := trace_api.NewTraceApiClient(conn)
		nowTime := time.Now().UnixMilli()
		res, err := client.ListRootSpanName(cmd.Context(), &trace_api.ListRootSpanNameRequest{
			AccessToken: cfg.SuperToken,
			Service: &trace_api.ServiceInfo{
				ServiceName:    serviceName,
				ServiceVersion: serviceVersion,
			},
			FromTime: nowTime - int64(listServiceCmd_pastHour)*3600*1000,
			ToTime:   nowTime,
		})
		if err != nil {
			return err
		}
		if res.Code != trace_api.ListRootSpanNameResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Println("root span name count", len(res.NameList))
		for _, name := range res.NameList {
			fmt.Println(name)
		}

		return nil
	},
}

func init() {
	listRootSpanNameCmd.Flags().Uint32Var(&listRootSpanNameCmd_pastHour, "pastHour", 1, "past hours from now")
}
